<template>
  <div class="ticket-list-container">
    <!-- 左侧工单列表 -->
    <div class="list-panel">
      <el-card>
        <template #header>
          <div class="card-header">
            <el-icon><List /></el-icon>
            <span>工单列表</span>
            <el-button 
              type="primary" 
              @click="goSubmit"
              style="margin-left: auto;"
            >
              <el-icon><Plus /></el-icon>
              新建工单
            </el-button>
          </div>
        </template>

        <!-- 搜索和筛选工具栏 -->
        <div class="toolbar">
          <el-row :gutter="16">
            <el-col :span="8">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索标题或描述"
                clearable
                @input="handleSearch"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-select v-model="statusFilter" placeholder="状态筛选" clearable>
                <el-option label="全部状态" value="" />
                <el-option label="待处理" value="OPEN" />
                <el-option label="处理中" value="IN_PROGRESS" />
                <el-option label="挂起" value="PENDING" />
                <el-option label="已解决" value="RESOLVED" />
                <el-option label="已关闭" value="CLOSED" />
                <el-option label="已取消" value="CANCELLED" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-select v-model="priorityFilter" placeholder="优先级筛选" clearable>
                <el-option label="全部优先级" value="" />
                <el-option label="低" value="LOW" />
                <el-option label="中" value="MEDIUM" />
                <el-option label="高" value="HIGH" />
                <el-option label="紧急" value="URGENT" />
                <el-option label="危急" value="CRITICAL" />
              </el-select>
            </el-col>
            <el-col :span="4">
              <el-button @click="resetFilters">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-col>
          </el-row>
        </div>

        <!-- 工单表格 -->
        <el-table 
          :data="paginatedTickets" 
          v-loading="loading"
          element-loading-text="加载中..."
          @row-click="handleRowClick"
          @selection-change="handleSelectionChange"
          style="width: 100%; margin-top: 20px;"
          :row-class-name="getRowClassName"
          highlight-current-row
        >
          <el-table-column type="selection" width="48" :selectable="isRowSelectable" />
          <el-table-column prop="ticketNumber" label="工单号" width="120" />
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ translateStatus(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="{ row }">
              <el-tag :type="getPriorityType(row.priority)" size="small">
                {{ translatePriority(row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类" width="100">
            <template #default="{ row }">
              {{ translateCategory(row.category) }}
            </template>
          </el-table-column>
          <el-table-column prop="assigneeName" label="负责人" width="100">
            <template #default="{ row }">
              {{ row.assigneeName || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="updatedAt" label="更新时间" width="160">
            <template #default="{ row }">
              {{ formatDate(row.updatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                size="small" 
                @click.stop="viewTicket(row)"
              >
                查看
              </el-button>
              <el-button 
                v-if="authStore.hasPermission(PERMISSIONS.TICKET_ASSIGN)"
                type="success" 
                size="small" 
                @click.stop="assignTicket(row)"
              >
                指派
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 空数据提示 -->
        <el-empty 
          v-if="!loading && paginatedTickets.length === 0" 
          description="暂无工单数据"
          :image-size="120"
        >
          <el-button type="primary" @click="goSubmit">创建第一个工单</el-button>
        </el-empty>

        <!-- 调试信息（开发环境） -->
        <el-alert
          v-if="!loading && ticketsCount === 0 && errorMessage"
          :title="`加载失败: ${errorMessage}`"
          type="error"
          :closable="false"
          style="margin-top: 20px;"
        />

        <!-- 批量操作 -->
        <div v-if="multipleSelection.length > 0" class="batch-actions">
          <el-alert
            :title="`已选择 ${multipleSelection.length} 个工单`"
            type="info"
            show-icon
            :closable="false"
          >
            <template #default>
              <el-button 
                v-if="authStore.hasPermission(PERMISSIONS.TICKET_ASSIGN)"
                type="primary" 
                size="small"
                @click="openBatchAssign"
                :loading="batchAssigning"
              >
                批量指派
              </el-button>
              <el-button size="small" @click="clearSelection">
                取消选择
              </el-button>
            </template>
          </el-alert>
        </div>

        <!-- 分页 -->
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="filteredTickets.length"
          layout="total, sizes, prev, pager, next, jumper"
          style="margin-top: 20px; text-align: right;"
        />
      </el-card>
    </div>

    <!-- 右侧详情面板 -->
    <div class="detail-panel" v-if="showDetailPanel">
      <el-card class="detail-card">
        <template #header>
          <div class="panel-header">
            <span>工单详情 #{{ selectedTicket?.id }}</span>
            <el-button 
              type="text" 
              @click="closeDetailPanel"
              class="close-btn"
            >
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
        </template>

        <div v-if="selectedTicket" class="ticket-detail">
          <!-- 基本信息 -->
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="标题">
              {{ selectedTicket.title }}
            </el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="getStatusType(selectedTicket.status)" size="small">
                {{ translateStatus(selectedTicket.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="优先级">
              <el-tag :type="getPriorityType(selectedTicket.priority)" size="small">
                {{ translatePriority(selectedTicket.priority) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="分类">
              {{ translateCategory(selectedTicket.category) }}
            </el-descriptions-item>
            <el-descriptions-item label="负责人">
              {{ selectedTicket.assigneeName || '未分配' }}
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ formatDate(selectedTicket.createdAt) }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">
              {{ formatDate(selectedTicket.updatedAt) }}
            </el-descriptions-item>
          </el-descriptions>

          <!-- 问题描述 -->
          <div class="description-section">
            <h4>问题描述</h4>
            <div class="description-content">
              {{ selectedTicket.description }}
            </div>
          </div>

          <!-- 操作按钮 -->
          <div class="action-buttons">
            <el-button 
              v-if="authStore.hasPermission(PERMISSIONS.TICKET_UPDATE)"
              type="primary" 
              @click="openStatusUpdate"
            >
              <el-icon><Edit /></el-icon>
              更新状态
            </el-button>
            <el-button 
              v-if="authStore.hasPermission(PERMISSIONS.TICKET_ASSIGN)"
              type="success" 
              @click="assignTicket(selectedTicket)"
            >
              <el-icon><User /></el-icon>
              指派工单
            </el-button>
          </div>

          <!-- 处理记录 -->
          <div class="history-section">
            <h4>处理记录</h4>
            <el-timeline>
              <el-timeline-item
                v-for="(log, idx) in selectedTicket.history || []"
                :key="idx"
                :timestamp="formatDate(log.time)"
                :type="getLogType(log.action)"
              >
                <div class="log-content">
                  <strong>{{ log.action }}</strong>
                  <p v-if="log.note">{{ log.note }}</p>
                </div>
              </el-timeline-item>
            </el-timeline>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 状态更新对话框 -->
    <el-dialog v-model="statusDialog.visible" title="更新工单状态" width="500px">
      <el-form :model="statusForm" label-width="80px">
        <el-form-item label="新状态">
          <el-select v-model="statusForm.status" placeholder="请选择状态">
            <el-option label="待处理" value="OPEN" />
            <el-option label="处理中" value="IN_PROGRESS" />
            <el-option label="挂起" value="PENDING" />
            <el-option label="已解决" value="RESOLVED" />
            <el-option label="已关闭" value="CLOSED" />
            <el-option label="已取消" value="CANCELLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input 
            v-model="statusForm.note" 
            type="textarea" 
            :rows="3"
            placeholder="请输入处理备注（可选）"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="statusDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="updating" @click="updateStatus">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 指派对话框 -->
    <el-dialog v-model="assignDialog.visible" title="指派工单" width="400px">
      <el-form label-width="80px">
        <el-form-item label="工单">
          <span>#{{ assignDialog.ticket?.id }} - {{ assignDialog.ticket?.title }}</span>
        </el-form-item>
        <el-form-item label="指派给">
          <el-select v-model="assignDialog.agentId" placeholder="选择技术人员">
            <el-option 
              v-for="agent in agents" 
              :key="agent.id" 
              :label="agent.name" 
              :value="agent.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="assignDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="assigning" @click="confirmAssign">确认</el-button>
      </template>
    </el-dialog>

    <!-- 批量指派对话框 -->
    <el-dialog v-model="batchAssignDialog.visible" title="批量指派工单" width="420px">
      <div style="margin-bottom: 12px; color:#606266;">
        已选择 {{ multipleSelection.length }} 个工单。
      </div>
      <el-form label-width="80px">
        <el-form-item label="指派给">
          <el-select v-model="batchAssignDialog.agentId" placeholder="选择技术人员">
            <el-option 
              v-for="agent in agents" 
              :key="agent.id" 
              :label="agent.name" 
              :value="agent.id" 
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="batchAssignDialog.visible = false">取消</el-button>
        <el-button type="primary" :loading="batchAssigning" @click="confirmBatchAssign">开始指派</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { computed, onMounted, ref, watch, reactive, nextTick } from 'vue'
import { useTicketsStore } from '../store/tickets'
import { useAuthStore, PERMISSIONS } from '../store/auth'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UserService } from '../services/users'

export default {
  name: 'TicketList',
  setup() {
    const ticketsStore = useTicketsStore()
    const authStore = useAuthStore()
    const router = useRouter()
    
    // 基础状态
    const searchKeyword = ref('')
    const statusFilter = ref('')
    const priorityFilter = ref('')
    const currentPage = ref(1)
    const pageSize = ref(10)
    const agents = ref([])
    
    // 右侧面板状态
    const showDetailPanel = ref(false)
    const selectedTicket = ref(null)
    
    // 对话框状态
    const assigning = ref(false)
    const updating = ref(false)
    const assignDialog = ref({ visible: false, ticket: null, agentId: null })
    const statusDialog = ref({ visible: false })
    const statusForm = reactive({ status: '', note: '' })
    
    // 批量操作状态
    const multipleSelection = ref([])
    const batchAssignDialog = ref({ visible: false, agentId: null })
    const batchAssigning = ref(false)

    onMounted(async () => {
      try {
        await ticketsStore.fetchTickets()
      } catch (error) {
        ElMessage.error('加载工单列表失败：' + (error.message || '未知错误'))
      }
      try {
        agents.value = await UserService.listAgents()
      } catch (error) {
        console.warn('加载技术人员列表失败:', error)
      }
    })

    const filteredTickets = computed(() => {
      const keyword = searchKeyword.value.toLowerCase()
      // 确保tickets是数组，如果不是则返回空数组
      const tickets = Array.isArray(ticketsStore.tickets) ? ticketsStore.tickets : []
      return tickets
        .filter(t => !statusFilter.value || t.status === statusFilter.value)
        .filter(t => !priorityFilter.value || t.priority === priorityFilter.value)
        .filter(t => !keyword || (t.title + ' ' + (t.description || '')).toLowerCase().includes(keyword))
    })

    // 工单数量和错误信息（用于模板显示）
    const ticketsCount = computed(() => {
      return Array.isArray(ticketsStore.tickets) ? ticketsStore.tickets.length : 0
    })

    const errorMessage = computed(() => {
      return ticketsStore.error || null
    })

    const paginatedTickets = computed(() => {
      const start = (currentPage.value - 1) * pageSize.value
      const end = start + pageSize.value
      return filteredTickets.value.slice(start, end)
    })

    // 行点击处理
    const handleRowClick = (row) => {
      selectedTicket.value = row
      showDetailPanel.value = true
    }

    // 查看工单
    const viewTicket = (row) => {
      // 跳转到工单详情页面
      router.push(`/tickets/${row.id}`)
    }

    // 关闭详情面板
    const closeDetailPanel = () => {
      showDetailPanel.value = false
      selectedTicket.value = null
    }

    // 指派工单
    const assignTicket = (row) => {
      assignDialog.value = { visible: true, ticket: row, agentId: row.assigneeId || null }
    }

    // 打开状态更新
    const openStatusUpdate = () => {
      if (!selectedTicket.value) return
      statusForm.status = selectedTicket.value.status
      statusForm.note = ''
      statusDialog.value.visible = true
    }

    // 更新状态
    const updateStatus = async () => {
      if (!selectedTicket.value || !statusForm.status) {
        ElMessage.warning('请选择要更新的状态')
        return
      }

      try {
        await ElMessageBox.confirm(
          `确定要将工单状态更新为"${translateStatus(statusForm.status)}"吗？`,
          '确认更新',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        updating.value = true
        const ticketId = selectedTicket.value.id
        const oldStatus = selectedTicket.value.status
        const newStatus = statusForm.status
        
        console.log(`[updateStatus] 开始更新状态: ticketId=${ticketId}, ${oldStatus} -> ${newStatus}`)
        
        const result = await ticketsStore.updateTicketStatus(ticketId, newStatus, statusForm.note)
        
        if (result.success) {
          console.log(`[updateStatus] ✅ 状态更新成功，新状态: ${newStatus}`)
          
          // 等待Vue响应式系统完成更新
          await nextTick()
          
          // 检查store中的数据是否已更新
          const storeTicket = ticketsStore.tickets.find(t => t.id === ticketId)
          console.log(`[updateStatus] Store中的工单状态:`, storeTicket?.status)
          
          // 更新右侧面板数据
          if (storeTicket) {
            selectedTicket.value = { ...storeTicket }
            console.log('✅ 右侧面板数据已更新，状态:', selectedTicket.value.status)
          }
          
          // 检查表格中的工单（考虑状态筛选）
          const tableTicket = paginatedTickets.value.find(t => t.id === ticketId)
          console.log(`[updateStatus] 表格中的工单状态:`, tableTicket?.status)
          console.log(`[updateStatus] 当前状态筛选:`, statusFilter.value)
          
          // 如果更新后的状态与当前筛选不符，工单会从列表中消失（这是正常的）
          // 但如果状态匹配筛选条件，应该能看到更新
          // 强制刷新列表以确保数据同步
          try {
            await ticketsStore.fetchTickets({
              page: currentPage.value - 1, // 转换为0基索引
              size: pageSize.value
            })
            
            // 等待响应式更新完成
            await nextTick()
            
            // 刷新后检查数据
            const refreshedTicket = ticketsStore.tickets.find(t => t.id === ticketId)
            if (refreshedTicket) {
              selectedTicket.value = { ...refreshedTicket }
              console.log('✅ 刷新后右侧面板数据，状态:', selectedTicket.value.status)
              
              // 如果更新后的状态导致工单不在当前筛选范围内，提示用户
              if (statusFilter.value && refreshedTicket.status !== statusFilter.value) {
                ElMessage.info(`工单状态已更新为"${translateStatus(refreshedTicket.status)}"，当前筛选条件已不匹配`)
              }
            }
          } catch (refreshError) {
            console.warn('刷新列表失败，但状态已更新:', refreshError)
            // 刷新失败不影响状态更新的成功提示
          }
          
          ElMessage.success('状态更新成功！')
          statusDialog.value.visible = false
        } else {
          ElMessage.error(result.message || '状态更新失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('状态更新失败：' + (error.message || '未知错误'))
        }
      } finally {
        updating.value = false
      }
    }

    const goSubmit = () => {
      router.push('/submit')
    }

    const handleSearch = () => {
      currentPage.value = 1
    }

    const resetFilters = () => {
      searchKeyword.value = ''
      statusFilter.value = ''
      priorityFilter.value = ''
      currentPage.value = 1
    }

    const handleSelectionChange = (rows) => {
      multipleSelection.value = rows
    }

    const clearSelection = () => {
      multipleSelection.value = []
    }

    const openBatchAssign = () => {
      if (!multipleSelection.value.length) return
      const available = multipleSelection.value.filter(t => 
        t.status !== 'RESOLVED' && t.status !== 'CLOSED' && t.status !== 'CANCELLED'
      )
      const resolvedCount = multipleSelection.value.length - available.length
      if (!available.length) {
        ElMessage.warning('选择项均为已完成工单，无法指派')
        return
      }
      if (resolvedCount > 0) {
        ElMessage.info(`已自动排除 ${resolvedCount} 个已完成工单`)
      }
      batchAssignDialog.value.visible = true
      batchAssignDialog.value.agentId = null
    }

    const confirmAssign = async () => {
      const ticket = assignDialog.value.ticket
      const agent = agents.value.find(a => a.id === assignDialog.value.agentId)
      if (!ticket || !agent) {
        ElMessage.warning('请选择要指派的技术人员')
        return
      }
      try {
        assigning.value = true
        const result = await ticketsStore.assignTicket(ticket.id, agent)
        
        if (result.success) {
          ElMessage.success('指派成功')
          
          // 更新右侧面板显示的数据
          if (selectedTicket.value && selectedTicket.value.id === ticket.id) {
            const updatedTicket = ticketsStore.tickets.find(t => t.id === ticket.id)
            if (updatedTicket) {
              selectedTicket.value = { ...updatedTicket }
            }
          }
          
          // 刷新工单列表以确保数据同步
          await ticketsStore.fetchTickets()
          
          assignDialog.value.visible = false
        } else {
          ElMessage.error(result.message || '指派失败')
        }
      } catch (error) {
        ElMessage.error('指派失败：' + (error.message || '未知错误'))
      } finally {
        assigning.value = false
      }
    }

    const confirmBatchAssign = async () => {
      const agent = agents.value.find(a => a.id === batchAssignDialog.value.agentId)
      if (!agent) {
        ElMessage.warning('请选择要指派的技术人员')
        return
      }
      if (!multipleSelection.value.length) {
        ElMessage.warning('请先选择要指派的工单')
        return
      }
      try {
        batchAssigning.value = true
        const targets = multipleSelection.value.filter(t => 
          t.status !== 'RESOLVED' && t.status !== 'CLOSED' && t.status !== 'CANCELLED'
        )
        const skipped = multipleSelection.value.length - targets.length
        const results = await Promise.allSettled(targets.map(t => ticketsStore.assignTicket(t.id, agent)))
        const success = results.filter(r => r.status === 'fulfilled').length
        const failed = results.length - success
        if (success) ElMessage.success(`成功指派 ${success} 个工单`)
        if (skipped) ElMessage.info(`已跳过 ${skipped} 个已完成工单`)
        if (failed) ElMessage.error(`有 ${failed} 个工单指派失败`)
        
        // 刷新工单列表以确保数据同步
        await ticketsStore.fetchTickets()
        
        // 如果当前选中的工单被更新了，刷新右侧面板
        if (selectedTicket.value && targets.some(t => t.id === selectedTicket.value.id)) {
          const updatedTicket = ticketsStore.tickets.find(t => t.id === selectedTicket.value.id)
          if (updatedTicket) {
            selectedTicket.value = { ...updatedTicket }
          }
        }
        
        batchAssignDialog.value.visible = false
        multipleSelection.value = []
      } catch (error) {
        ElMessage.error('批量指派失败：' + (error.message || '未知错误'))
      } finally {
        batchAssigning.value = false
      }
    }

    const isRowSelectable = (row) => row.status !== 'RESOLVED' && row.status !== 'CLOSED' && row.status !== 'CANCELLED'

    const getRowClassName = ({ row }) => {
      if (row.status === 'OPEN') return 'pending-row'
      if (row.status === 'IN_PROGRESS') return 'in-progress-row'
      if (row.status === 'RESOLVED') return 'resolved-row'
      if (row.status === 'CLOSED') return 'closed-row'
      if (row.status === 'CANCELLED') return 'cancelled-row'
      return ''
    }

    const getStatusType = (status) => {
      const types = {
        OPEN: 'info',
        IN_PROGRESS: 'primary',
        PENDING: 'warning',
        RESOLVED: 'success',
        CLOSED: 'info',
        CANCELLED: 'danger'
      }
      return types[status] || 'info'
    }

    const getPriorityType = (priority) => {
      const types = {
        LOW: 'info',
        MEDIUM: 'success',
        HIGH: 'warning',
        URGENT: 'danger',
        CRITICAL: 'danger'
      }
      return types[priority] || 'info'
    }

    const getLogType = (action) => {
      if (action.includes('创建')) return 'primary'
      if (action.includes('状态更新')) return 'success'
      if (action.includes('处理')) return 'warning'
      return 'info'
    }

    const translateStatus = (status) => ({
      OPEN: '待处理',
      IN_PROGRESS: '处理中',
      PENDING: '挂起',
      RESOLVED: '已解决',
      CLOSED: '已关闭',
      CANCELLED: '已取消'
    }[status] || status)

    const translatePriority = (priority) => ({
      LOW: '低',
      MEDIUM: '中',
      HIGH: '高',
      URGENT: '紧急',
      CRITICAL: '危急'
    }[priority] || priority)

    const translateCategory = (category) => ({
      system: '系统问题',
      feature: '功能问题',
      performance: '性能问题',
      other: '其他'
    }[category] || category)

    const formatDate = (ts) => {
      if (!ts) return '-'
      const d = new Date(ts)
      return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')} ${String(d.getHours()).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')}`
    }

    // 监听筛选条件变化，重置到第一页
    watch([statusFilter, priorityFilter], () => {
      currentPage.value = 1
    })

    return { 
      loading: computed(() => ticketsStore.loading),
      authStore,
      PERMISSIONS,
      filteredTickets, 
      paginatedTickets,
      ticketsCount,
      errorMessage,
      searchKeyword, 
      statusFilter, 
      priorityFilter,
      currentPage,
      pageSize,
      showDetailPanel,
      selectedTicket,
      statusDialog,
      statusForm,
      updating,
      goSubmit,
      handleSearch,
      resetFilters,
      handleRowClick,
      viewTicket,
      closeDetailPanel,
      assignTicket,
      openStatusUpdate,
      updateStatus,
      getRowClassName,
      getStatusType,
      getPriorityType,
      getLogType,
      translateStatus, 
      translatePriority,
      translateCategory,
      formatDate,
      agents,
      assigning,
      assignDialog,
      confirmAssign,
      multipleSelection,
      handleSelectionChange,
      clearSelection,
      openBatchAssign,
      batchAssignDialog,
      batchAssigning,
      confirmBatchAssign,
      isRowSelectable 
    }
  }
}
</script>

<style scoped>
.ticket-list-container {
  display: flex;
  height: calc(100vh - 80px);
  gap: 16px;
  padding: 16px;
}

.list-panel {
  flex: 1;
  min-width: 0;
}

.detail-panel {
  width: 400px;
  flex-shrink: 0;
}

.detail-card {
  height: 100%;
  overflow-y: auto;
}

.panel-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.close-btn {
  padding: 4px;
}

.ticket-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.description-section h4,
.history-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.description-content {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 8px;
  white-space: pre-wrap;
  line-height: 1.6;
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.log-content {
  padding: 8px 0;
}

.log-content strong {
  color: #303133;
  font-size: 14px;
}

.log-content p {
  margin: 4px 0 0 0;
  color: #606266;
  font-size: 13px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
}

.toolbar {
  margin-bottom: 20px;
}

.batch-actions {
  margin-top: 16px;
}

/* 表格行样式 */
:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: var(--bg-tertiary);
}

:deep(.pending-row) {
  background-color: #fef7e6;
}

:deep(.in-progress-row) {
  background-color: #e6f7ff;
}

:deep(.resolved-row) {
  background-color: #f6ffed;
}

:deep(.closed-row) {
  background-color: #f0f0f0;
}

:deep(.cancelled-row) {
  background-color: #fff2f0;
}

/* 分页样式 */
:deep(.el-pagination) {
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .detail-panel {
    width: 350px;
  }
}

@media (max-width: 768px) {
  .ticket-list-container {
    flex-direction: column;
    height: auto;
  }
  
  .detail-panel {
    width: 100%;
    height: 400px;
  }
  
  .action-buttons {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .ticket-list-container {
    padding: 8px;
    gap: 8px;
  }
  
  .toolbar .el-row {
    flex-direction: column;
    gap: 8px;
  }
  
  .toolbar .el-col {
    width: 100%;
  }
}
</style>